import { listQuestionBankVOByPage } from "@/api/question-bank"
import { batchAddQuestionsToBank } from "@/api/question-bank-question"
import { Button, Form, message, Modal, Select } from "antd"
import React, { useEffect, useState } from "react"

interface Props {
  questionIdList?: number[]
  visible: boolean
  onSubmit: () => void
  onCancel: () => void
}

/**
 * 批量向题库添加题目弹窗
 *
 * @param props
 * @constructor
 */
const BatchAddQuestionsToBankModal: React.FC<Props> = (props) => {
  const { questionIdList = [], visible, onSubmit, onCancel } = props
  const [form] = Form.useForm()
  const [questionBankList, setQuestionBankList] = useState<QuestionBankVO[]>([])

  // 全量获取所有题库
  const getQuestionBankList = async () => {
    try {
      const res = await listQuestionBankVOByPage({
        pageSize: 200,
        sortField: "createTime",
        sortOrder: "descend"
      })
      setQuestionBankList(res.data?.records ?? [])
    } catch (error) {
      error instanceof Error && message.error("获取题库列表失败，" + error.message)
    }
  }

  useEffect(() => {
    getQuestionBankList()
  }, [])

  const doSubmit = async (value: { questionBankId: number }) => {
    const hide = message.loading("正在操作")
    try {
      await batchAddQuestionsToBank({
        questionIdList,
        questionBankId: value.questionBankId
      })
      hide()
      message.success("操作成功")
      onSubmit?.()
    } catch (error) {
      hide()
      error instanceof Error && message.error("操作失败，" + error.message)
    }
  }

  return (
    <Modal
      destroyOnClose
      title={"批量向题库添加题目"}
      open={visible}
      footer={null}
      onCancel={() => {
        onCancel?.()
      }}
    >
      <Form form={form} style={{ marginTop: 24 }} onFinish={doSubmit}>
        <Form.Item label="所属题库" name="questionBankId">
          <Select
            style={{ width: "100%" }}
            options={questionBankList.map((questionBank) => ({
              label: questionBank.title,
              value: questionBank.id
            }))}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  )
}
export default BatchAddQuestionsToBankModal
